package com.qiku.dao.impl;

import com.qiku.dao.ResourceDao;
import com.qiku.dao.UserDao;
import com.qiku.pojo.Resource;
import com.qiku.pojo.User;
import com.qiku.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.*;

public class ResourceDaoImpl implements ResourceDao {
    private QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
    private UserDao userDao = new UserDaoImpl();

    /**
     * //根据资源名或者上传用户名、资源类型查询资源
     *
     * @param resourceName 资源名
     * @param userName     上传用户名
     * @param type         资源类型
     * @return
     */
    @Override
    public List<Map<String, String>> findByNameOrUserName(String resourceName, String userName, String type) {
        try {
            String sql = "select * from resource where is_audit=1";
            StringBuilder sb = new StringBuilder(sql);
            List<Object> list = new ArrayList<>();
            String[] types = null;
            if (resourceName != null && "".equals(resourceName)) {
                sb.append(" and resource_name like ?");
                resourceName = "%" + resourceName + "%";
                list.add(resourceName);
            }
            if (userName != null && "".equals(userName)) {
                sb.append(" and uploader_id = ?");
                User user = userDao.findUserByName(userName);
                list.add(user.getId());
            }
            if (type != null && "".equals(type)) {
                switch (type) {
                    case "img":
                        sb.append(" and type in(?,?,?,?,?,?,?,?)");
                        types = new String[]{"jpeg", "jpg", "png", "bmp", "gif", "svg", "raw", "ico"};
                        break;
                    case "music":
                        sb.append(" and type in(?,?,?,?,?)");
                        types = new String[]{"mp3", "flac", "acc", "wav", "midi"};
                        break;
                    case "text":
                        sb.append(" and type in(?,?,?,?,?,?)");
                        types = new String[]{"txt", "md", "pdf", "doc", "docx", "rtf"};
                        break;
                    case "video":
                        sb.append(" and type in(?,?,?,?,?,?,?,?)");
                        types = new String[]{"mp4", "avi", "mkv", "flv", "ogg", "m4v", "mov", "rmvb"};
                        break;
                    case "zip":
                        sb.append(" and type in(?,?,?,?)");
                        types = new String[]{"zip", "7z", "rar", "exe"};
                        break;
                }
                if (types != null) {
                    Collections.addAll(list, types);
                }
            }
            List<Resource> resourceList = qr.query(sb.toString(), new BeanListHandler<>(Resource.class), list.toArray());
            List<Map<String, String>> mapList = new ArrayList<>();
            for (Resource r : resourceList) {
                Map<String, String> map = new HashMap<>();
                User user = userDao.findUserById(r.getUploader_id());
                r.setUser(user);
                String resource_id = r.getId();
                String resource_name = r.getResource_name();
                String uploader_name = r.getUser().getUsername();
                String upload_date = r.getUpload_date();
                String rType = r.getType();
                String img_url = r.getImg_url();
                String file_url = r.getFile_url();
                map.put("resource_id", resource_id);
                map.put("resource_name", resource_name);
                map.put("uploader_name", uploader_name);
                map.put("upload_date", upload_date);
                map.put("type", rType);
                map.put("img_url", img_url);
                map.put("file_url", file_url);
                mapList.add(map);
            }
            return mapList;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Map<String, String>> findResourceList(int num) {
        try {
//            查询全部资源信息
            String sql = "select * from resource where is_audit = 1 OR is_audit = ?";
//            查询到的信息集合
            List<Resource> resourceList = qr.query(sql, new BeanListHandler<>(Resource.class), num);
//            声明一个list集合存储响应的信息
            List<Map<String, String>> list = new ArrayList<>();
//            遍历信息集合
            for (Resource r : resourceList) {
                Map<String, String> map = new HashMap<>();
                User user = userDao.findUserById(r.getUploader_id());
//                将userDao获取到的user信息设置到resource里
                r.setUser(user);
//                获取需要响应的信息并将其存放到map集合里
                String resourceId = r.getId();
                String resourceName = r.getResource_name();
                String uploaderName = r.getUser().getUsername();
                String uploadDate = r.getUpload_date();
                String file_url = r.getFile_url();
                String type = r.getType();
                String is_audit = r.getIs_audit() + "";
                map.put("resource_id", resourceId);
                map.put("resource_name", resourceName);
                map.put("uploader_name", uploaderName);
                map.put("upload_date", uploadDate);
                map.put("type", type);
                map.put("is_audit", is_audit);
                map.put("file_url", file_url);
                list.add(map);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //根据资源id查询资源信息
    @Override
    public Resource findResourceById(String id) {
        try {
            //准备sql
            String sql = "select * from resource where id = ?";
            //执行sql
            Resource resource = qr.query(sql, new BeanHandler<>(Resource.class), id);
            return resource;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Resource> findResourceListByType(String type) {
        try {
            String sql = "select * from resource where is_audit = 1";
            StringBuilder sb = new StringBuilder(sql);
            String[] types = null;
            switch (type) {
                case "img":
                    sb.append(" and type in(?,?,?,?,?,?,?,?)");
                    types = new String[]{"jpeg", "jpg", "png", "bmp", "gif", "svg", "raw", "ico"};
                    break;
                case "music":
                    sb.append(" and type in(?,?,?,?,?)");
                    types = new String[]{"mp3", "flac", "acc", "wav", "midi"};
                    break;
                case "text":
                    sb.append(" and type in(?,?,?,?,?,?)");
                    types = new String[]{"txt", "md", "pdf", "doc", "docx", "rtf"};
                    break;
                case "video":
                    sb.append(" and type in(?,?,?,?,?,?,?,?)");
                    types = new String[]{"mp4", "avi", "mkv", "flv", "ogg", "m4v", "mov", "rmvb"};
                    break;
                case "zip":
                    sb.append(" and type in(?,?,?,?)");
                    types = new String[]{"zip", "7z", "rar", "exe"};
                    break;
            }
            System.out.println("Type:" + Arrays.toString(types));
            List<Resource> resourceList = qr.query(sb.toString(), new BeanListHandler<>(Resource.class), Arrays.stream(types).toArray());
            return resourceList;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 向数据库中插入文件
     *
     * @param resource 文件对象
     * @return 1表示插入成功，0表示失败
     */
    @Override
    public int updateResource(Resource resource) {
        try {
            String sql = "insert into resource (id,resource_name,uploader_id,upload_date,type,img_url,file_url,is_audit)" +
                    "values (?,?,?,?,?,?,?,?)";
            int update = qr.update(sql,
                    resource.getId(), resource.getResource_name(),
                    resource.getUploader_id(), resource.getUpload_date(),
                    resource.getType(), resource.getImg_url(),
                    resource.getFile_url(), resource.getIs_audit());
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    //逻辑删除资源
    public Integer deleteResource(String resourceId) {
        try {
            String sql = "update resource set is_audit = 0 where id = ?";
            int i = qr.update(sql, resourceId);
            return i;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    //逻辑恢复资源
    public Integer recoverResource(String resourceId) {
        try {
            String sql = "update resource set is_audit = 1 where id = ?";
            int i = qr.update(sql, resourceId);
            return i;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}
